<template>
  <div class="passwordModify">
    <!--修改登录密码-->
    <div class="password_certification" @keyup.13="eventshow($event)">
      <ul>
        <li>
          <label>{{lang['Current Password']}}</label>
          <input type="password" name="" value="" v-model="oldpassword" ref="oldpassword" :placeholder="lang['please original password']">
        </li>
        <li class="passwordHover">
          <label>{{lang['new password']}}</label>
          <input type="password" maxlength="20" :placeholder="lang['43015']" v-model="password" ref="password" >
        </li>
        <li>
          <div class="strength">
            {{lang['register_passwordHint']}}
          </div>
        </li>
        <li>
          <label>{{lang['register_confirmPassword']}}</label>
          <input type="password" name="" value="" v-model="password2" ref ="password2" :placeholder="lang['please enter the confirmation new secret']">
        </li>

         <li>
          <label v-if="AreaCodeData !== '' ">{{lang['smsAuthenticationCode']}}</label>
          <label v-if="AreaCodeData === '' ">{{lang['mailboxVerificationCode']}}</label>
          <input type="text" name="" maxlength="6" value="" class="inptYz"  v-model="verifyCode" ref="verifyCode" :placeholder="lang.register_PleaseerificationCode" >
          <!-- -->
          <a class="countryAreaNo">
            <span v-if="sendMsgDisabled" style="color:rgba(255,255,255,.7);">{{lang['register_ClickGett']}}({{time}})</span>
            <span v-if="!sendMsgDisabled" v-bind:class="{colorActive: !isSendSMS}" @click="sendphone">{{lang['register_ClickGet']}}</span>
          </a>
        </li>
         <li>
          <button type="button" class="submitBtn" v-bind:class="{ active: !isSubmitBtnCheck }" @click="submitMondifyPassword"> {{lang['determineBth']}} </button>
        </li>
      </ul>
    </div>

    <!-- 弹窗 提示-->
    <SwModal :isShow.sync="showModal" modalClass="userModal smallModal" :isShowBg="true" :isCloseOnClickBg="true" :onClosed="onClosed"  :okText="lang['determineBth']" :ok="passwordBtndetermine">
      <div class="successfulOperation">
        <p>{{lang['revise password successfully']}}</p>
      </div>
    </SwModal>

  </div>
</template>
<script>
import SwModal from '@/components/SwModal'
import ModalApi from '@/components/SwModal/api.js'
import CheckInput from '@/utils/CheckInput.js'
import rules from '@/utils/rules.js'
import LoginService from '@/service/LoginService.js'

export default {
  props: [
    'lang',
    'langKey',
    'getCustomer'
  ],
  data () {
    return {
      showModal: false,
      time: 60,
      sendMsgDisabled: false,
      password: '',
      passwordLevel: 0,
      phone_emali: '',
      password2: '',
      oldpassword: '',
      verifyCode: '',
      AreaCodeData: '',
      sendCodeulr: '',
      isSendSMS: true,
      isSubmitBtnCheck: true
    }
  },
  components: {
    SwModal
  },
  methods: {
    // 发送验证码
    sendphone () {
      if (!this.isSendSMS) { return }
      // 原密密码、新密码、确认密码、是否为空
      this.checkHandle.chackByIdsInOrder(['oldpassword', 'password', 'password2'])
      .then((info) => {
        if (!info.isValid) {
          // info.error()
          ModalApi.message(info.error(), '', '', 'userModal')
          return
        }
        this.isSendSMS = false
        if (this.AreaCodeData) {
          this.sendCodeulr = 'Security/SendSmsByCode'
        } else {
          this.sendCodeulr = 'Security/SendMailByCode'
        }
        this.$http.post(this.sendCodeulr, {
          AreaCode: this.AreaCodeData,
          VerifyDeviceType: 0,
          VerifyCode: '',
          PhoneOrEmail: this.phone_emali,
          BussinessType: 4,
          LanguageCode: this.langKey || ''
        }, {
          modalOptions: {
            modalClass: 'userModal'
          }
        })
        .then((res) => {
          if (res.StatusCode === '200') {
            // 倒计时
            let me = this
            me.sendMsgDisabled = true
            let interval = window.setInterval(() => {
              if ((me.time--) <= 0) {
                me.time = 60
                me.sendMsgDisabled = false
                window.clearInterval(interval)
              }
            }, 1000)
            // 倒计时
            ModalApi.message(this.lang['VerificationCodeSuccessful'], '', '', 'userModal')
          }
          this.isSendSMS = true
        })
      })
      .catch((info) => {
      })
    },
    eventshow (ev) {
      if (ev.keyCode === 13) {
        this.submitMondifyPassword()
      }
    },
    submitMondifyPassword () {
      if (!this.isSubmitBtnCheck) { return }
      // 原密密码、新密码、确认密码、验证码是否为空
      this.checkHandle.chackByIdsInOrder(['oldpassword', 'password', 'password2', 'verifyCode'])
      .then((info) => {
        if (!info.isValid) {
          // info.error()
          ModalApi.message(info.error(), '', '', 'userModal')
          return
        }
        this.isSubmitBtnCheck = false
        this.$http.post('Security/ChangeLoginPwd', {
          oldPwd: this.oldpassword,
          newPwd: this.password,
          pin: this.verifyCode,
          passwordLevel: this.passwordLevel
        }, {
          modalOptions: {
            modalClass: 'userModal'
          }
        })
        .then((res) => {
          if (res.StatusCode === '200') {
            this.oldpassword = ''
            this.password = ''
            this.password2 = ''
            this.verifyCode = ''
            this.sendMsgDisabled = false
            this.showModal = !this.showModal
          }
          this.isSubmitBtnCheck = true
        })
      })
      .catch((info) => {
      })
    },
    passwordBtndetermine () {
      this.showModal = false
      this.$emit('GetCustomerList')
    },
    onClosed () {
      this.$nextTick(() => {
        LoginService.logout()
        this.$router.push({path: '/user/login'})
      })
    }
  },
  watch: {
    getCustomer () {
      if (this.getCustomer.Phone) {
        this.phone_emali = this.getCustomer.Phone
        this.AreaCodeData = this.getCustomer.AreaCode.substring(1)
      } else {
        this.phone_emali = this.getCustomer.Email
        this.AreaCodeData = ''
      }
    }
  },
  mounted () {
    let that = this
    this.checkHandle = new CheckInput({
      rules: rules,
      trimValue (val, item) {
        return val.replace(/^\s+|\s+$/, '')
      },
      list: [
        {
          id: 'oldpassword',
          input: that.$refs.oldpassword,
          rules: [
            {
              rule: 'required',
              error () {
                return that.lang['please original password']
              }
            }
          ]
        },
        {
          id: 'password',
          input: that.$refs.password,
          rules: [
            {
              rule: 'required',
              error () {
                that.passwordLevel = 0
                return that.lang['43015']
              }
            },
            {
              rule (val) {
                let isValid = true
                let level = 0
                let pwd = val
                let hasLetter = /[a-zA-Z]/.test(pwd) // 拥有字母
                let hasUpperLetter = /[A-Z]/.test(pwd) // 拥有大写字母
                let hasLowerLetter = /[a-z]/.test(pwd) // 拥有小写字母
                let hasNumber = /\d/.test(pwd) // 拥有数字
                let hasSymbol = /[^a-zA-Z0-9]/.test(pwd) // 拥有字符
                let minLength = 8 // 最小8位
                let groups = 0 // 密码强度 0不通过 1弱 2中 3强

                // 得到组合种类数量
                groups = [hasLetter, hasNumber, hasSymbol].filter((v) => v === true).length

                // 至少是8位和拥有两种组合才通过
                if (pwd.length >= minLength && groups >= 2) {
                  // 有两种组合为弱
                  if (groups >= 2) level = 1
                  // 有两种组合且同时拥有大小写为中
                  if (groups >= 2 && hasUpperLetter && hasLowerLetter) level = 2
                  // 拥有三种组合为中
                  if (groups >= 3) level = 2
                  // 拥有三种组合且同时拥有大小写为强
                  if (groups >= 3 && hasUpperLetter && hasLowerLetter) level = 3
                } else {
                  isValid = false
                }

                that.passwordLevel = level

                return isValid
              },
              error () {
                return that.lang['please enter the correct password']
              }
            },
            {
              rule (val) {
                return that.password !== that.oldpassword
              },
              error () {
                return that.lang['new password match old']
              }
            }
          ]
        },
        {
          id: 'password2',
          input: that.$refs.password2,
          rules: [
            {
              rule: 'required',
              error () {
                return that.lang['please enter the confirmation new secret']
              }
            },
            {
              rule (val) {
                return that.password === that.password2
              },
              error () {
                return that.lang['register_PleaseconfirmPasswordErr']
              }
            }
          ]
        },
        {
          id: 'verifyCode',
          input: that.$refs.verifyCode,
          rules: [
            {
              rule: 'required',
              error () {
                return that.lang['register_PleaseerificationCode']
              }
            }
          ]
        }
      ]
    })
  }
}
</script>

<style lang="less">

.passwordModify{
  background: #1A1F2B ;
  padding-bottom: 20px;

  .password_certification{
    width: 420px;
    margin: 0 auto;
  }
  .password_certification  li{
    position: relative;
    label{
      display: block;
      padding: 15px 10px 5px;
      height: 20px;
      line-height: 20px;
      color: #fff;
    }
    input{
      padding: 0 10px;
      width: 100%;
      height: 40px;
      line-height: 40px;
      border-radius: 2px;
      box-sizing: border-box;
      background-color: #2A3440;
      color: #fff;
      font-size: 12px;

      &.inptYz{
        padding-right: 120px;
      }
    }
    .countryAreaNo {
      position: absolute;
      top: 40px;
      right: 0;
      width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      span {
        display: block;
        font-size: 12px;
        &.colorActive {
         color: #ccc
        }
      }
      &:after{
        content: "";
        position: absolute;
        left: 0;
        top: 10px;
        display: block;
        width: 1px;
        height: 20px;
        border-right: solid 1px #B1BBC2;
      }
    }
  }

  .submitBtn {
    width: 50%;
    display: block;
    height: 40px;
    line-height: 40px;
    margin: 20px auto 0;
    text-align: center;
    background: #3782FF;
    color: #fff;
    font-size: 12px;
    border-radius: 2px;
    cursor: pointer;
    &.active{
      background-color: #2A3441;
      cursor:not-allowed;
    }
  }
  .passwordHover{

    & + li .strength{
      margin: 5px 10px 0;
      display: none;
      font-size: 10px;
      color: #3782FF;
    }
    &:hover + li .strength{
      display: block;
      color: #3782FF;
    }
  }
}
</style>
